package com.tangyee.home_knowledge.acticity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.LinearLayout;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tangyee.R;
import com.tangyee.home_blood_center.utils.DialogUtils;
import com.tangyee.home_knowledge.adapter.KnowledgeSortExpandListAdapter;
import com.tangyee.home_knowledge.bean.KnowledgeContent;
import com.tangyee.home_knowledge.bean.KnowledgeContentItem;
import com.tangyee.home_knowledge.util.ConstantUtil;
import com.tangyee.home_knowledge.util.HttpUtil;
import com.tangyee.home_knowledge.view.AnimatedExpandableListView;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * @author: yu huawen
 * @date: 2019/1/30 11:33
 */
public class KnowledgeSortActivity extends AppCompatActivity {

    // 请求参数的值
    private int requestParamValue = 0;
    // 一共需要请求的次数
    private int sumRequestCount = 1;
    // 当前是第几次请求
    private int currentRequestNum = 1;

    private Handler handler;
    private Handler httpHandler;
    private Dialog dialog;

    private LinearLayout sortBackKnowledge;

    private AnimatedExpandableListView expandableListView;
    private KnowledgeSortExpandListAdapter knowledgeSortExpandListAdapter;

    private List<KnowledgeContent> knowledgeContentList;
    private List<KnowledgeContentItem> currentRequestList;
    private List<KnowledgeContentItem> parentContentList;

    @SuppressLint("HandlerLeak")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 禁止横屏,感觉这里没有必要横屏
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        // 这个 Dialog 的调用的是 home_blood_center 里的
        dialog = DialogUtils.createLoadingDialog(this, "加载中...");
        // 这个 handler 用于控制加载页面布局
        handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case ConstantUtil.SUCCESS:
                        // 请求成功，并且有目录
                        setContentView(R.layout.activity_knowledge_sort);
                        init();
                        break;
                    case ConstantUtil.FALL:
                        // 请求失败
                        break;
                    case ConstantUtil.FINISH:
                        // 请求成功，没有目录
                        break;
                }

                DialogUtils.closeDialog(dialog);
            }
        };

        knowledgeContentList = new ArrayList<>();

        loadKnowledgeContent();

    }

    private void init(){
        sortBackKnowledge = (LinearLayout)findViewById(R.id.sort_back);

        expandableListView = (AnimatedExpandableListView) findViewById(R.id.knowledge_expand_listview);
        knowledgeSortExpandListAdapter = new KnowledgeSortExpandListAdapter(this, knowledgeContentList);
        expandableListView.setAdapter(knowledgeSortExpandListAdapter);

        setListener();
    }

    /**
     * 网络请求，加载知识目录
     */
    private void loadKnowledgeContent(){
        // 设置 get 请求的参数（page, pageSize）
        LinkedHashMap<String, String> params = new LinkedHashMap<>();
        params.put(ConstantUtil.contentParamName, requestParamValue + "");

        HttpUtil.sendRequest(ConstantUtil.knowledgeContentURL, params, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // 通知请求失败
                Message message = handler.obtainMessage();
                message.what = ConstantUtil.FALL;
                handler.sendMessage(message);
            }
            /**
             * 这里不在 UI 线程里面
             * @param call
             * @param response
             * @throws IOException
             */
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                // 使用轻量级的Gson解析得到的json
                String responseData = response.body().string();
                System.out.println(responseData);
                Type listType = new TypeToken<List<KnowledgeContentItem>>(){}.getType();
                Gson gson = new Gson();
                currentRequestList = new ArrayList<>();
                currentRequestList = gson.fromJson(responseData, listType);

                /**
                 * 得到一个完整的目录（一级、二级）这里只能串行得到，所以我通过递归来请求
                 */

                // 如果是第一次请求（得到一级目录），并且请求得到的 item 数大于零，则说明还要继续请求（去得到二级目录）
                if (currentRequestList.size() > 0 && currentRequestNum == 1){ // 第一次
                    // 保存请求到的一级目录
                    parentContentList = currentRequestList;
                    sumRequestCount = currentRequestList.size() + 1;
                    // 设置第二次请求的参数值
                    requestParamValue++;
                    // 开始第二次请求
                    currentRequestNum++;
                    loadKnowledgeContent();
                }else if (currentRequestList.size() == 0 && currentRequestNum == 1){ // 第一次请求，但没有请求到目录
                    // 通知请求成功完成
                    Message message = handler.obtainMessage();
                    message.what = ConstantUtil.SUCCESS;
                    handler.sendMessage(message);
                } else if (currentRequestNum < sumRequestCount){ // 第一次到最后一次之间
                    // 保存一级目录及其子目录，并建立联系
                    KnowledgeContent knowledgeContent = new KnowledgeContent();
                    knowledgeContent.setParentItem(parentContentList.get(currentRequestNum - 2));
                    knowledgeContent.setChildListItem(currentRequestList);
                    knowledgeContentList.add(knowledgeContent);
                    // 设置下一次请求的参数值
                    requestParamValue += currentRequestList.size() + 1;
                    // 开始下一此请求
                    currentRequestNum++;
                    loadKnowledgeContent();
                }else { // 最后一次请求
                    // 保存一级目录及其子目录，并建立联系
                    KnowledgeContent knowledgeContent = new KnowledgeContent();
                    knowledgeContent.setParentItem(parentContentList.get(currentRequestNum - 2));
                    knowledgeContent.setChildListItem(currentRequestList);
                    knowledgeContentList.add(knowledgeContent);

                    // 通知请求成功完成
                    Message message = handler.obtainMessage();
                    message.what = ConstantUtil.SUCCESS;
                    handler.sendMessage(message);
                }

            }
        });
    }

    /**
     * 设置组件的监听事件
     */
    private void setListener(){

        sortBackKnowledge.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });

        expandableListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @SuppressLint("ResourceAsColor")
            @Override
            public boolean onGroupClick(ExpandableListView parent, View view, int i, long l) {
                /**
                 * // 点击parent 时，启动相应的展开和收缩动画
                 */
                if(knowledgeContentList.get(i).getChildListItem().size() > 0) { // 一级目录有二级内容才有动画
                    if (expandableListView.isGroupExpanded(i)) {
                        expandableListView.collapseGroupWithAnimation(i); // 收缩
                    } else {
                        expandableListView.expandGroupWithAnimation(i); // 展开
                    }

                    return true;
                }
                // 如果一级目录下没有二级目录，点击则跳转
                Intent intent = new Intent(KnowledgeSortActivity.this, KnowledgeSortExpandActivity.class);
                Bundle bundle = new Bundle();
                int preCount = 1;
                for (int j = 0; j < i ; j++){ // 在这里得出请求这一级目录时，前面请求了多少次,为了得到 parentId
                    preCount += knowledgeContentList.get(j).getChildListItem().size();
                }
                // 一级目录
                bundle.putInt(ConstantUtil.sortExpandParamNameSupCls, preCount + i);
                // 没有二级目录，赋值 0
                bundle.putInt(ConstantUtil.sortExpandParamNameSubCls, 0);
                // 标题
                bundle.putString("title", knowledgeContentList.get(i).getParentItem().getCategory());
                intent.putExtras(bundle);
                startActivity(intent);

                return false;
            }
        });
        expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View view, int i, int i1, long l) {
                Intent intent = new Intent(KnowledgeSortActivity.this, KnowledgeSortExpandActivity.class);
                Bundle bundle = new Bundle();
                // 一级目录
                bundle.putInt(ConstantUtil.sortExpandParamNameSupCls, knowledgeContentList.get(i).getChildListItem().get(i1).getParentId());
                System.out.println("i:" + i + "i1:" + i1 + knowledgeContentList.get(i).getChildListItem().get(i1).getParentId());
                // 二级目录
                bundle.putInt(ConstantUtil.sortExpandParamNameSubCls, knowledgeContentList.get(i).getChildListItem().get(i1).getParentId() + i1 + 1);
                // 标题
                bundle.putString("title", knowledgeContentList.get(i).getChildListItem().get(i1).getCategory());
                intent.putExtras(bundle);
                startActivity(intent);
                return false;
            }
        });
        // 控制只能打开一个组
        expandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
            @Override
            public void onGroupExpand(int groupPosition) {
                int count = knowledgeContentList.size();
                for(int i = 0 ; i < count ; i++) {
                    if (i != groupPosition) {
                        expandableListView.collapseGroup(i);
                    }
                }
            }
        });
    }
}
